//
//  Buy1ViewController.swift
//  jiaoyi
//
//  Created by wjk on 2018/8/14.
//  Copyright © 2018年 wjk. All rights reserved.
//

import UIKit
import UIAlertController_Blocks
import ZSDropDownMenu
import MJRefresh
import SwiftyJSON

class Buy1ViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource,BuyCellDelegate {

    var dataArray:[JSON] = [JSON]()
    
    var categories: [AutionCategory] = {
        let cat = [AutionCategory]()
        return cat
    }()
    
    
    lazy var catergrayView: Buy1DropCategrayView? = {
       let catergrayViews = Bundle.main.loadNibNamed("Buy1DropCategrayView", owner: nil, options: nil) as? [UIView]
        
        let v = catergrayViews?.first as? Buy1DropCategrayView
        v?.frame = self.view.bounds
        return v
    }()
    
    lazy var dropDateView: Buy1DropDateView? = {
        let dateViews = Bundle.main.loadNibNamed("Buy1DropDateView", owner: nil, options: nil) as? [UIView]
        return dateViews?.first as? Buy1DropDateView
    }()
    
    var columnTwoArray = ["2018-1-1","2018-2-3"]
    var TopTitleArr = ["品种","交易日期"]//日期格式：2018-11-11
    
    var type: Int?    
    var categoryId: Int?
    var benginAt: String?
    var endAt: String?
    var page: Int = 1
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initDrop()
        
        initFilterBlcok()
        
        
        tableView.register(R.nib.buyTableViewCell(), forCellReuseIdentifier: "buyTableViewCell")
        tableView.rowHeight = 214;

        let header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.loadData()
        })
        
        tableView.mj_header = header
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.loadData(isMore: true)
        })
//        tableView.mj_header.beginRefreshing()
        
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.page = 1
        self.loadData()
    }
    
    
    func initFilterBlcok() {
        catergrayView?.selectItemBlock = {[weak self] (category) in
            if let id = category.id {
                self?.categoryId = id
                self?.loadData()
            }
            
        }
        
        
        dropDateView?.selectedBlock = {[weak self] (begin,end) in
            self?.benginAt = begin
            self?.endAt = end
            
            self?.loadData()
        }
        
    }
    
     func initDrop() {
   
        
        guard let catergrayView = catergrayView,let dropDateView = dropDateView  else {
            return
        }
        
        let dropDownViews: [UIView] = [catergrayView, dropDateView]
        
        
        let FFA409 = UIColor.init(red: 64/255, green: 143/255, blue: 205/255, alpha: 1.0)
        
        // Inherit YNDropDownView if you want to hideMenu in your dropDownViews
        let view = YNDropDownMenu(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 46), dropDownViews: dropDownViews, dropDownViewTitles: ["品种", "交易日期"])
        
         view.setImageWhen(normal: UIImage(named: "home_arraw_nor"), selected: UIImage(named: "home_arraw_sel"), disabled: UIImage(named: "home_arraw_nor"))
        
        
        view.setLabelColorWhen(normal: .black, selected: FFA409, disabled: .gray)
        //            view.setLabelColorWhen(normalRGB: "000000", selectedRGB: "FFA409", disabledRGB: "FFA409")
        
        view.setLabelFontWhen(normal: .systemFont(ofSize: 12), selected: .boldSystemFont(ofSize: 12), disabled: .systemFont(ofSize: 12))
        //            view.setLabel(font: .systemFont(ofSize: 12))
        
        view.backgroundBlurEnabled = true
        //            view.bottomLine.backgroundColor = UIColor.black
        view.bottomLine.isHidden = false
        // Add custom blurEffectView
        let backgroundView = UIView()
        backgroundView.backgroundColor = .black
        view.blurEffectView = backgroundView
        view.blurEffectViewAlpha = 0.7
        
        view.setBackgroundColor(color: UIColor.white)
        self.view.addSubview(view)
    }
    
    func loadData(isMore: Bool = false){
        if isMore == true {
            page += 1
        }else{
            page = 1
        }
        
        NetWorkRequest(.fair(type: type, direction: BuyViewController.defalut.direction, categoryId: categoryId, beginAt: benginAt, endAt: endAt, page: page, trade_type:"1")) { [weak self] (response) -> (Void) in
            let resnew = JSON(response);
            if resnew["code"].stringValue == "000000"{
                let res = resnew["data"].dictionaryValue
                self?.page = (res["fairs"]?.dictionaryValue["current_page"]?.intValue)!
                let models = res["fairs"]?.dictionaryValue["data"]?.arrayValue
                                                                
                self?.getCategories(json: res["options"]?.dictionaryValue["categories"]?.arrayObject)
                
                if isMore == true {
                    if models!.count == 0 {
                        self?.tableView.mj_footer.endRefreshingWithNoMoreData()
                    }else{
                        self?.tableView.mj_footer.endRefreshing()
                    }
                }else{
                    self?.dataArray.removeAll()
                    
                    self?.tableView.mj_footer.resetNoMoreData()
                    self?.tableView.mj_header.endRefreshing()
                    
                }
                models?.forEach({ (jd) in
                    self?.dataArray.append(jd)
                })
                
                self?.tableView.reloadData()
            }
            
        }
    }
    
    func getCategories(json: [Any]?){
        if categories.count > 0 {
            return
        }
        json?.forEach({ (anyObj) in
            if let dic = anyObj as? [String: Any]{
                if let model = AutionCategory(JSON: dic){
                    categories.append(model)
                }
            }
        })
        catergrayView?.categories = categories
        
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "buyTableViewCell") as! BuyTableViewCell
        cell.delegate = self
        let model = self.dataArray[indexPath.row]
        cell.model = model
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func zhuanClick(_ cell: BuyTableViewCell) {
        
        let row = self.tableView.indexPath(for: cell)?.row
        let da = self.dataArray[row!]
        let vc = R.storyboard.home.guaListViewController()!.showType(t: 0)
        vc.fair_id = da["id"].stringValue
        vc.type_name = da["name"].stringValue
        vc.trade_type_text = da["trade_type_text"].stringValue
        vc.trade_date = da["trade_date"].stringValue
        vc.websocket = da["websocket_url"].stringValue
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func anpai(_ cell: BuyTableViewCell) {
        let vc = R.storyboard.home.biaoListViewController()!
        vc.id = self.dataArray[(self.tableView.indexPath(for: cell)?.row)!]["id"].stringValue
        vc.type = 0
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
